<template>
    <div class=''>
        计算属性 watch {{ computedVal }}
        <input type="text" v-model="obj.age">
        <input type="text" v-model="obj.name">
    </div>
    <div @click="btn">修改值</div>
    <div @click="stopClick">stop停止watchEffect</div>
</template>

<script lang='ts' setup>

import { reactive, computed, watch, watchEffect, ref } from 'vue';
let obj = reactive({ name: '165', age: '111' })
let refVal = ref({ name: '165', age: '111' })
// 计算属性
const computedVal = computed(() => {
    return obj.age + obj.name
})
//情况一：监视ref定义的响应式数据
watch(refVal, (newValue, oldValue) => {
    console.log('obj变化了1', newValue, oldValue)
}, { immediate: true })

//情况二：监视多个ref定义的响应式数据
watch([obj], (newValue, oldValue) => {
    console.log('sum或msg变化了2', newValue, oldValue)
})

/* 情况三：监视reactive定义的响应式数据
            若watch监视的是reactive定义的响应式数据，则无法正确获得oldValue！！
            若watch监视的是reactive定义的响应式数据，则强制开启了深度监视 
*/
watch(obj, (newValue, oldValue) => {
    console.log('person变化了3', newValue, '---', oldValue)
}, { immediate: true, deep: false }) //此处的deep配置不再奏效

//情况四：监视reactive定义的响应式数据中的某个属性
watch(() => obj.name, (newValue, oldValue) => {
    console.log('person的job变化了4', newValue, oldValue)
}, { immediate: true, deep: true })

//情况五：监视reactive定义的响应式数据中的某些属性
watch([() => obj.name, () => obj.age], (newValue, oldValue) => {
    console.log('person的job变化了5', newValue, oldValue)
}, { immediate: true, deep: true })

//特殊情况
watch(() => obj.name, (newValue, oldValue) => {
    console.log('person的job变化了6', newValue, oldValue)
}, { deep: true }) //此处由于监视的是reactive素定义的对象中的某个属性，所以deep配置有效


const btn = () => {
    obj.name = '1111'
    obj.age = '1111'
    refVal.value.age = '1111'
}
const stop = watchEffect((effect) => {
    effect(() => {
        console.log('===>watchEffect回调代码执行前执行',);
    })
    console.log('===>watchEffect', obj.age);
}, {
    flush: 'pre',  // 组件执行前
    // flush: 'sync',强制效果始终同步触发
    // flush: 'post'组件更新后
})
// 停止jwatchEffect
const stopClick = () => stop()
</script>

<style scoped lang='less'></style>